package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

import file.Loader;
import file.Saver;

public class Connection extends Thread {
	Socket connection;

	public Connection(Socket connection) {
		this.connection = connection;
		System.out.println("Got connection from: "
				+ connection.getInetAddress().getHostAddress());

	}

	public void run() {
		InputStreamReader inputStreamReader = null;
		BufferedReader input = null;
		PrintStream output = null;

		try {
			inputStreamReader = new InputStreamReader(
					connection.getInputStream());
			input = new BufferedReader(inputStreamReader);
			output = new PrintStream(connection.getOutputStream());
			String readLine = "";
			StringBuffer sb = new StringBuffer();
			while ((readLine = input.readLine()) != null) {
				System.out.println(connection.getInetAddress().toString()
						+ " - " + readLine);
				if (readLine.contains("NOHOMO")) {
					break;
				} else {
					sb.append(readLine);
				}
			}
			String message = sb.toString();
			if (message.startsWith("log-master message")) {
				Saver.save(message);
				output.print("EY OK");
				output.flush();
			} else if (message.startsWith("log-master request")) {
				String notes = Loader.load(message);
				System.out.println("Sending notes to: "
						+ connection.getInetAddress().toString());
				System.out.print("---\n" + notes + "\n---\n");
				output.print(notes);
				output.flush();
				output.print("EY OK");
				output.flush();
			} else {
				// wrong type of message
			}

			System.out.println("Closing down: "
					+ connection.getInetAddress().toString());
			output.close();
			input.close();
			inputStreamReader.close();
			connection.close();
			return;

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}